﻿using Retail.Models.DBModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Wholesaler.Models.DBModels;
using Yunzuan.Foundation.Configurations;
using Yunzuan.Foundation.Exceptions;
using Yunzuan.Foundation.Log;
using YunZuan.Models;

namespace Yunzuan.Foundation.DataAccess
{
    public class YZ
    {
        private static readonly object lockHelper = new object();
        private static Dictionary<string, IDataContext> dataContextStore = new Dictionary<string, IDataContext>();

        private static readonly string LOG_FILE_PATH = AppDomain.CurrentDomain.BaseDirectory + "\\Yunzuan.log";
        private static void WriteLog(string msg)
        {
            using (StreamWriter sw = new StreamWriter(LOG_FILE_PATH, true, Encoding.UTF8))
            {
                sw.WriteLine(msg);
            }
        }

        private YZ()
        { 
        }

        static YZ()
        {
            System.IO.FileSystemWatcher watcher = new FileSystemWatcher(IBatisConfig.SQL_MAP_CONFIG_PATH);
            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.WaitForChanged(WatcherChangeTypes.Changed, 1000);
            watcher.Changed += (sender, evt) =>
            {
                watcher.EnableRaisingEvents = false;
                WriteLog(DateTime.Now.ToString() + "\t检测到配置文件更新：" + evt.FullPath);
                lock (lockHelper)
                {
                    dataContextStore.Clear();
                }
                watcher.EnableRaisingEvents = true;
            };
            watcher.EnableRaisingEvents = true;
        }

        /// <summary>
        /// 获取数据库操作上下文对象，多数据库时使用
        /// </summary>
        /// <param name="name">配置文件</param>
        /// <param name="count">给多一次重连的机会</param>
        /// <returns></returns>
        public static IDataContext GetDatabase(string name,int count=3)
        {
            if (!string.IsNullOrEmpty(name)&&!dataContextStore.ContainsKey(name))
            {
                lock (lockHelper)
                {
                    if (!dataContextStore.ContainsKey(name))
                    {
                        if (count > 0)
                        {
                            try
                            {
                                DataContext ctx = new DataContext(name);
                                dataContextStore.Add(name, ctx);
                            }
                            catch (Exception ex)
                            {
                                // ibatis中加载typeAlias时报错：The error occurred while loading SqlMap. 实例化一个sqlMap.config 的typeAlias对应的类
                                Link link = new Link(); //YunZuan.Models
                                CustomerRemarks orderInfo = new CustomerRemarks();  //Wholesaler.Models.DBModels
                                Index_Appointment index_Appointment = new Index_Appointment(); // Retail.Models.DBModels
                                count--;
                                Logger.Error(typeof(YZ), $"第{(3-count)}次\t加载配置文件异常\t" + ex.Message + ex.StackTrace);
                                GetDatabase(name, count);
                                //throw new WarnException("E10000001: 加载配置文件异常, 详情请查看配置文件." + ex.Message);
                            }
                        }
                    }
                }
            }
            return dataContextStore[name];
        }

        /// <summary>
        /// 事务查询
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ITransaction GetTransaction(string name)
        {
            return new Transaction(name);
        }
         
        public static ITransaction Transaction
        {
            get
            {
                return GetTransaction(string.Empty);
            }
        }

        /// <summary>
        /// 数据服务
        /// </summary>
        public static IDataContext Database
        {
            get
            {
                return GetDatabase(string.Empty);
            }
        }

        /// <summary>
        /// 获取数据库事务统计数据
        /// </summary>
        /// <remarks>监控事务阻塞情况</remarks>
        /// <returns>状态字符串</returns>
        public static string GetStatisticInfo()
        {
            return string.Format("[DataContext Count:{0}], [Transaction Count:{1}]", dataContextStore.Count, Yunzuan.Foundation.DataAccess.Transaction.GetTransactionCount());
        }
    }
}
